package com.dundun.aspect;

import com.dundun.annotation.AuthCheck;
import com.dundun.common.utils.DundunJwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author eterlar
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            AuthCheck authCheck = hm.getMethodAnnotation(AuthCheck.class);
            if (null == authCheck) {
                return true;
            }
            String token = request.getHeader("authorization");
            if(DundunJwtUtil.verifyToken(token)==true){
                return true;
            }else{
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }

        }
        return true;
    }
}
